package com.lyun.interceptor;

import com.lyun.common.BaseContext;
import com.lyun.common.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 每次会在控制台输出一下具体的请求路径 并在每次请求时在线程中写入id
 */
public class MovementServiceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        System.out.println(request.getRequestURI());

        String token = request.getHeader("Authorization");
        System.out.println("MovementServiceInterceptor...token = " + token);

        if ("admin".equals(token)) {
            return true;
        }

        Claims claims = JwtUtils.getClaims(token);
        Object id = claims.get("id");
        if (id == null) {
            return false;
        }
        System.out.println("MovementServiceInterceptor...id = " + id);

        BaseContext.setCurrentId(((Integer) id).longValue());

        return true;
    }
}